package spotview;

import com.sun.spot.util.Utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

public class Node {

    public static final int MAX_QUEUE_SIZE = 10;
    DeviceHandler device;
    Vector messages;
    int msgPtr;
    int queueSize;
    MainFrame frame;
    // DEBUG
    boolean listenmode = false;

    Node(DeviceHandler aThis, MainFrame frame) {
        this.messages = new Vector(MAX_QUEUE_SIZE);
        this.frame = frame;
        frame.setNode(this);
        queueSize = MAX_QUEUE_SIZE;
        device = aThis;
        msgPtr = 0;
    }

    public void onReceived(byte[] data) {
        DataInput input = new DataInputStream(new ByteArrayInputStream(data));
        try {
            Message msg = Message.decode(input);
            System.out.println("Message from" + msg.getSender() + " " + msg.getBody());
            pushMessage(msg);
            frame.onMessageReceived(msg);
        } catch (IOException ex) {
            System.out.println("Unable to decode message.");
        }
    }

    void pushMessage(Message receivedMessage) {
        if (messages.contains(receivedMessage)) {
            return;
        }
        messages.addElement(receivedMessage);
        System.out.println("Pushed");
    }

    void dropMessage() {
        messages.removeElementAt(0);
    }

    Message nextMessage() {
        if (messages.isEmpty()) {
            return null;
        }
        while (messages.size() > queueSize) {
            dropMessage();
        }
        Message ret = (Message) messages.elementAt(msgPtr);
        msgPtr = (msgPtr + 1) % messages.size();
        return ret;
    }

    void sendMessage(Message msg) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutput output = new DataOutputStream(baos);
        System.out.println("Sending:" + msg.getBody());
        try {
            msg.writeTo(output);
        } catch (IOException e) {
            System.out.println("Failed to encode message");
        }
        device.send(baos.toByteArray());
        try {
            baos.close();
        } catch (IOException e) {
            System.out.println("Failed to Free buffer");
        }
    }

    void work() {
        while (true) {
            Message next = nextMessage();
            if (next != null && !listenmode) {
                sendMessage(next);
            }
            Utils.sleep(1000);
        }
    }
}
